<template>
  <div id="pro_discount">
    <div id="system_member">
      <!--顶部搜索框内容开始-->

      <div class="role_seek">
        <el-input
          class="role_input"
          placeholder="请输入优惠券标题"
          v-model="forms.distitle"
          clearable
          @change="seek"
        ></el-input>

        <el-select v-model="forms.type" placeholder="请选择优惠券类型">
          <el-option
            v-for="item in seekType"
            :key="item.typeData"
            :label="item.typeName"
            :value="item.typeData"
          >
          </el-option>
        </el-select>
        <el-select v-model="forms.statuss" placeholder="请选择优惠券状态">
          <el-option
            v-for="item in seekStatus"
            :key="item.staData"
            :label="item.staName"
            :value="item.staData"
          >
          </el-option>
        </el-select>

        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="seek"
          v-power="'promote:coupon:query'"
          >查找</el-button
        >
        <el-button size="mini" type="primary" icon="el-icon-edit" @click="add" v-power="'promote:coupon:create'"
          >添加</el-button
        >
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-download"
          @click="exper"
          >当前页导出</el-button
        >
        <!--修改添加弹出框开始-->
        <el-dialog :title="title" :visible.sync="dialogFormVisible">
          <el-form
            :model="form"
            :rules="rules"
            ref="form"
            class="pop-up"
            status-icon
            label-position="left"
          >
            <el-form-item
              prop="title"
              label="优惠券名称"
              :label-width="formLabelWidth"
            >
              <el-input v-model="form.title" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item
              prop="type"
              label="优惠券类型"
              :label-width="formLabelWidth"
            >
              <el-select v-model="form.type" placeholder="请选择优惠券类型">
                <el-option
                  v-for="item in type"
                  :key="item.typeData"
                  :label="item.typeName"
                  :value="item.typeData"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="介绍" :label-width="formLabelWidth">
              <el-input
                v-model="form.description"
                autocomplete="off"
              ></el-input>
            </el-form-item>

            <el-form-item
              prop="total"
              label="优惠券数量"
              :label-width="formLabelWidth"
            >
              <el-input
                placeholder="请输入内容"
                v-model.number="form.total"
                class="input-with-select"
              >
                <el-button slot="append">张</el-button>
              </el-input>
            </el-form-item>

            <el-form-item
              prop="limit"
              label="每人限领"
              :label-width="formLabelWidth"
            >
              <el-input
                placeholder="请输入内容"
                v-model.number="form.limit"
                class="input-with-select"
              >
                <el-button slot="append">张</el-button>
              </el-input>
            </el-form-item>

            <el-form-item
              prop="discount"
              label="满减金额"
              :label-width="formLabelWidth"
            >
              <el-input
                placeholder="请输入内容"
                v-model.number="form.discount"
                class="input-with-select"
              >
                <el-button slot="append">元</el-button>
              </el-input>
            </el-form-item>

            <el-form-item
              prop="min"
              label="最低消费"
              :label-width="formLabelWidth"
            >
              <el-input
                placeholder="请输入内容"
                v-model.number="form.min"
                class="input-with-select"
              >
                <el-button slot="append">元</el-button>
              </el-input>
            </el-form-item>

            <el-form-item
              prop="status"
              label="优惠券状态"
              v-model="status"
              :label-width="formLabelWidth"
            >
              <el-select v-model="form.status" placeholder="请选择">
                <el-option
                  v-for="item in status"
                  :key="item.staData"
                  :label="item.staName"
                  :value="item.staData"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-radio-group style="margin-bottom: 30px;"> </el-radio-group>

            <el-form-item label="有效期" :label-width="formLabelWidth">
              <el-radio-group v-model="period">
                <el-radio-button :label="0" :disabled="disableds"
                  >领券相对天数</el-radio-button
                >
                <el-radio-button :label="1" :disabled="disableds"
                  >指定绝对时间</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item v-show="period === 0">
              <el-input
                placeholder="请输入内容"
                class="input-with-select periodinput"
                v-model="form.days"
                :disabled="disableds"
              >
                <el-button slot="append">天</el-button>
              </el-input>
            </el-form-item>
            <el-form-item v-show="period === 1">
              <el-date-picker
                :disabled="disableds"
                v-model="form.gmtStart"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker
              >至
              <el-date-picker
                :disabled="disableds"
                v-model="form.gmtEnd"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="商品限制范围" :label-width="formLabelWidth">
              <el-radio-group v-model="bools">
                <el-radio-button :label="0" :disabled="disableds"
                  >全场通用</el-radio-button
                >
                <el-radio-button :label="1" :disabled="disableds"
                  >指定分类</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item v-show="bools === 0" v-if="upDisabled === 'update'">
              <el-input :disabled="disableds" />
            </el-form-item>
            <el-form-item
              v-show="bools === 1"
              label="优惠类目"
              :label-width="formLabelWidth"
            >
              <el-cascader
                :disabled="disableds"
                :options="spulist"
                ref="dom"
                v-model="form.categoryId"
                :props="{ checkStrictly: true }"
              ></el-cascader>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="bool ? adduser('form') : compile('form')"
              >确 定</el-button
            >
          </div>
        </el-dialog>
        <!--修改添加弹出框结束-->
      </div>
      <!--顶部搜索框内容结束-->

      <!--底部列表内容部分-->
      <template>
        <el-table
          border
          :data="tableData"
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column
            prop="id"
            label="优惠券ID"
            sortable
            align="center"
          ></el-table-column>
          <el-table-column
            prop="title"
            label="优惠券名称"
            align="center"
          ></el-table-column>

          <el-table-column label="优惠券类型" align="center">
            <template slot-scope="scope">
              {{ scope.row.type | typeMe }}
            </template>
          </el-table-column>

          <el-table-column
            label="介绍"
            prop="description"
            align="center"
          ></el-table-column>

          <el-table-column label="优惠券数量" prop="total" align="center">
          </el-table-column>

          <el-table-column
            label="剩余数量"
            prop="surplus"
            align="center"
          ></el-table-column>

          <el-table-column
            label="每人限领"
            prop="limit"
            align="center"
          ></el-table-column>

          <el-table-column label="满减金额" align="center"
            ><template slot-scope="scope"
              >满减{{ scope.row.discount }}元</template
            ></el-table-column
          >

          <el-table-column label="最低消费" align="center">
            <template slot-scope="scope"
              >满{{ scope.row.min }}元可用</template
            ></el-table-column
          >

          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-tag> {{ scope.row | statusMe() }}</el-tag
              ><!--将整个对象数据传递下去-->
            </template>
          </el-table-column>

          <el-table-column label="使用类目名称" align="center">
            <template slot-scope="scope">
              <el-tag> {{ scope.row.categoryTitle | categorytitleMe }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="categoryId" label="使用类目ID" align="center">
          </el-table-column>

          <el-table-column prop="days" label="领券相对天数" align="center">
          </el-table-column>

          <el-table-column label="领券开始时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.gmtStart | filterTime }}</span>
            </template>
          </el-table-column>

          <el-table-column label="领券结束时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.gmtEnd | filterTime }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="address"
            label="操作"
            width="300px"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                class="button_redact"
                size="mini"
                @click="state(scope.row)"
              >
                {{ scope.row | buttonMe() }}
              </el-button>
              <el-button
                class="button_redact"
                size="mini"
                @click="handleEdit(scope.row)"
                v-power="'promote:coupon:update'"
                >编辑</el-button
              >
              <el-button
                class="button_remove"
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                v-power="'promote:coupon:delete'"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!--底部列表内容部分结束-->

      <!--底部分页开始-->
      <div class="block">
        <Paging :forms="forms" :gain="gain"></Paging
        ><!--分页封装-->
      </div>
      <!--底部分页结束-->
    </div>
  </div>
</template>

<script>
import Discount from "@/api/promotion/Discount"; //引入封装
import Paging from "../../components/Paging.vue"; //自定义组件
export default {
  data() {
    return {
      //弹出框
      tableData: [{}], //table里面的数据
      dialogFormVisible: false, //控制弹出框是否显示
      formLabelWidth: "100px", //弹出框宽度
      title: "创建", //弹出框标题
      bool: true, //布尔值 判断编辑还是修改 为true是创建 否则就是修改
      upDisabled: "", //用于判断
      update: "", //用于判断
      bools: 0, //优惠券类型
      period: 0,
      disableds: true, //是否禁用

      //选择框
      seekType: [
        { typeData: 1, typeName: "满减券" },
        { typeData: null, typeName: "全部" }
      ],
      type: [{ typeData: 1, typeName: "满减券" }],
      seekStatus: [
        { staData: 1, staName: "正常" },
        { staData: 0, staName: "下架" },
        { staData: -1, staName: "已过期" },
        { staData: null, staName: "全部" }
      ],
      status: [
        { staData: 1, staName: "正常" },
        { staData: 0, staName: "下架" }
      ],
      //输入框数值
      form: {
        title: "", //优惠券昵称
        limit: 0, //用户限制领取
        min: 0, //最低消费(满足优惠的最低价格)
        description: "", //优惠券描述
        discount: 0, //优惠价格
        total: 0, //优惠券总数
        categoryId: "", //优惠类别
        days: "", //优惠时长
        gmtStart: "", //优惠开始时间
        gmtEnd: "", //优惠结束时间
        status: 1, //优惠券状态
        surplus: "",
        type: 1, //优惠券类型
        id: "" //优惠券id
      },
      forms: {
        limit: 10, //页码长度
        total: 5, //分页——-共几条
        pageNo: 1, //页码
        type: "", //类型
        statuss: "", //状态
        distitle: "" //index框输入内容
      },

      //弹出框正则验证
      rules: {
        //优惠券标题
        title: [
          { message: "优惠券名称不能为空", trigger: "change", required: true }
        ],
        //最低消费验证
        min: [
          { message: "每人限领不能为空", trigger: "change", required: true },
          { pattern: /^[0-9]*$/, message: "请输入整数" }
        ],
        //优惠价格验证
        discount: [
          { message: "每人限领不能为空", trigger: "change", required: true },
          { pattern: /^[0-9]*$/, message: "请输入整数" }
        ],
        //优惠券数量验证
        total: [
          { message: "每人限领不能为空", trigger: "change", required: true },
          { pattern: /^[0-9]*$/, message: "请输入整数" }
        ],
        //每人限领验证
        limit: [
          { message: "每人限领不能为空", trigger: "change", required: true },
          { pattern: /^[0-9]*$/, message: "请输入整数" }
        ]
      },

      //点击当前的下标
      spulist: [{}], //用于递归
      formclone: [{}] //克隆form初始化数据
    };
  },
  components: {
    //注册组件
    Paging
  },
  created() {
    this.gain();
    Discount.spu().then(res => {
      this.spulist = res.data.data;
      this.getTreeData(this.spulist);
      this.formclone = JSON.parse(JSON.stringify(this.form)); //将弹出框初始化状态克隆一份
    });
  },
  filters: {
    //操作状态过滤器
    buttonMe(data) {
      if (new Date().getTime() > data.gmtEnd) {
        return "已过期"; //判断是否已过期
      } else if (data.status == 0) {
        return "激活";
      } else {
        return "冻结";
      }
    },
    //类型过滤器
    typeMe(data) {
      if (data == 1) {
        return "满减卷";
      } else {
        return "错误类型";
      }
    },
    //状态过滤器
    statusMe(data) {
      if (new Date().getTime() > data.gmtEnd) {
        return "已过期"; //判断是否已过期
      } else if (data.gmtEnd == "") {
        if (data.status == 1) {
          return "正常";
        } else {
          return "下架";
        }
      } else if (data.status == 1) {
        return "正常";
      } else {
        return "下架";
      }
    },
    //类目过滤器
    categorytitleMe(data) {
      if (data == null) {
        return "全部类目";
      } else {
        return data;
      }
    }
  },
  methods: {
    //用户当前状态
    state(row) {
      Discount.state(row.id, row.status ? 0 : 1).then(res => {
        if (res.data.errmsg == "成功") {
          if (new Date().getTime() > row.gmtEnd) {
            //判断已过期的内容
            this.Prosperity.Messages("过期优惠券 建议删除", "error");
          } else {
            this.Prosperity.Messages("修改优惠券成功", "success");
            this.gain();
          }
        }
      });
    },
    //获取列表数据内容
    gain() {
      var _this = this;
      Discount.gain(_this.forms).then(res => {
        _this.tableData = res.data.data.items; //将接口列表内容赋值给列表数组
        _this.forms.limit = res.data.data.limit; //页码长度
        _this.forms.pageNo = res.data.data.pageNo; //页码
        _this.forms.total = res.data.data.total;
      });
    },
    //点击添加按钮触发
    add() {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
      this.form = JSON.parse(JSON.stringify(this.formclone)); //将form初始状态再次赋值给form表单
      this.bools = 0; //将弹出框显示设为初始值
      this.period = 0; //将弹出框显示设为初始值
      this.bool = true; //bool为true触发添加接口
      this.disableds = false; //将弹出框禁用取消
      this.dialogFormVisible = true; //显示弹出框
    },
    //添加新角色接口
    adduser(form) {
      var _this = this;
      if (_this.form.gmtEnd == "" && _this.form.days == "") {
        //判断是否选择了时间

        this.Prosperity.Messages("请填写优惠卷使用区间息", "error");
      } else {
        if (_this.form.gmtStart !== "" && _this.form.gmtEnd !== "") {
          //判断时间是否为空
          _this.form.gmtStart = new Date(_this.form.gmtStart).getTime();
          _this.form.gmtEnd = new Date(_this.form.gmtEnd).getTime();
        }
        this.$refs[form].validate(valid => {
          if (valid) {
            if (_this.form.categoryId) {
              //判断是否选择了类目 类目里有没有数据
              _this.form.categoryId = _this.$refs.dom.getCheckedNodes()[0].data.value;
            }
            Discount.adduser(_this.form)
              .then(res => {
                if (res.data.errmsg == "成功") {
                  _this.gain();
                  this.Prosperity.Messages("添加角色成功", "success");
                  this.dialogFormVisible = false;
                } else {
                  this.Prosperity.Messages(res.data.errmsg, "error");
                }
              })
              .catch(err => {
                return err;
              });
          } else {
            return false;
          }
        });
      }
    },
    //点击编辑按钮触发
    handleEdit(row) {
      this.$nextTick(() => {
        //清空输入框下面的提示（输入错误）
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
      this.disableds = true; //禁用输入框

      if (row.days == undefined && row.gmtStart) {
        //当天数为空日期有内容时显示日期否则默认显示日期
        this.period = 1;
      } else {
        this.period = 0;
      }
      if (row.categoryId == undefined) {
        //当没类别没有值时 隐藏选择框
        this.bools = 0;
      } else {
        this.bools = 1;
      }
      //获取到数据在点击进去时赋值入输入框
      this.form = { ...row };
      if (new Date().getTime() > row.gmtEnd) {
        //如果状态是已过期则显示-1
        this.form.status = -1;
      }

      this.bool = false; //改变bool 触发编辑接口
      this.title = "编辑"; //改变弹出框标题
      this.dialogFormVisible = true; //显示弹出框
    },

    //编辑角色接口
    compile(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          var _this = this;
          if (_this.form.gmtStart && _this.form.gmtEnd) {
            _this.form.gmtStart = new Date(_this.form.gmtStart).getTime();
            _this.form.gmtEnd = new Date(_this.form.gmtEnd).getTime();
          }
          //判断是否选择优惠类目
          if (_this.form.categoryId) {
            _this.form.categoryId = _this.$refs.dom.getCheckedNodes()[0].data.value;
          }
          Discount.compile(_this.form).then(res => {
            if (res.data.errmsg == "成功") {
              _this.gain(); //重新渲染接口
              this.Prosperity.Messages("编辑角色成功", "success");
              this.dialogFormVisible = false;
            } else {
              this.Prosperity.Messages("编辑角色失败", "error");
            }
          });
        } else {
          return false;
        }
      });
    },
    //搜索信息
    seek() {
      this.forms.pageNo = 1; //在最后一页搜索时回到第一页
      this.gain();
    },

    //点击删除当前内容
    handleDelete(row) {
      this.form.id = row.id; //当前删除行的优惠券id
      this.$confirm("此操作将永久删除该内容, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //确定删除的话
          this.cancel();
        })
        .catch(() => {
          this.Prosperity.Messages("取消删除成功", "warning");
        });
    },
    //删除管理员内容接口
    cancel() {
      var _this = this;
      Discount.cancel(_this.form)
        .then(res => {
          if (res.data.errmsg == "成功") {
            this.gain(); //渲染数据
            this.Prosperity.Messages("删除成功", "success");
            _this.dialogFormVisible = false;
          } else {
            this.Prosperity.Messages(res.data.errmsg, "error");
          }
        })
        .catch(err => {
          return err;
        });
    },
    //导出Ex表格
    exper() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/util/Export2Excel");
        const tHeader = [
          "优惠券ID",
          "名称",
          "介绍",
          "类型",
          "最低消费",
          "减免金额",
          "每人限领",
          "优惠券数量",
          "剩余数量",
          "状态",
          "使用类目"
        ];
        const filterVal = [
          "id",
          "title",
          "description",
          "type",
          "min",
          "discount",
          "limit",
          "total",
          "surplus",
          "status",
          "cateotry"
        ];
        const list = this.tableData;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "优惠券信息");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    //递归
    getTreeData(data) {
      for (let item in data.length) {
        if (data[item].children.length < 1) {
          data[item].children = undefined;
        } else {
          this.getTreeData(data[item].children);
        }
      }
    }
  }
};
</script>

<style scoped="scoped">
/*最大父盒子开始*/
#system_member {
  padding: 20px;
}
/*最大父盒子结束*/

/*顶部index框开始*/
.el-select {
  margin-right: 5px;
}
.el-input {
  width: 200px !important;
  height: 40px !important;
  margin-right: 5px;
}
.role_seek > .el-input > .el-input__inner {
  font-size: inherit;
  width: 100% !important;
  height: 100% !important;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

/*顶部index框结束*/

/*顶部按钮开始*/
.role_seek > .el-button--primary {
  line-height: 1px;
  font-size: 14px;
  border: 1px solid #409eff !important;
  background: #409eff !important;
  color: #fff;
  vertical-align: middle;
  padding: 12px 20px;
  margin-left: 5px;
}
/*顶部按钮结束*/

/*底部列表内容*/

.el-table {
  margin-top: 23px;
  font-size: 12px;
}
.el-table td {
  text-align: center !important;
}
.cell {
  font-size: 12px;
  padding: 0px 10px;
}
.el-table__row > td {
  padding: 8px 0px;
}
.button_redact {
  background: #409eff !important;
  color: #fff !important;
  border: 1px solid #409eff;
}
/*编辑内容按钮*/
.button_redact:hover {
  background: #66b1ff !important;
  border: 1px solid #66b1ff;
}
.button_remove {
  background: #f56c6c !important;
  color: #fff !important;
  border: #f56c6c 1px solid;
}
.button_remove:hover {
  background: #f78989 !important;
  border: 1px solid #f78989;
}
.el-table--scrollable-x .el-table__body-wrapper {
  overflow-x: hidden;
}
/*底部列表内容*/

/*底部分页*/
.block {
  margin: 55px 0px;
}

.el-select .el-input .el-select__caret {
  position: absolute;
  right: 150px;
}
/*底部分页结束*/

/*添加弹出框*/
.el-form {
  margin-left: 55px;
}
.el-input__inner {
  text-indent: 5px;
}
.el-form-item {
  text-align: none !important;
}
.el-input__suffix {
  left: none !important;
}
/* .el-tabs__item:hover{border: 1px solid #333!important;color: #333;background:#409EFF!important;} */
.el-tabs__nav-wrap::after {
  height: 0px !important;
}
.periodinput {
  margin-left: 100px;
}
/*添加弹出框结束*/
</style>
